<?php
// +----------------------------
// | Created by PhpStorm
// +----------------------------
// | Author: YnnSon
// +----------------------------
namespace app\admin\controller;

use app\api\controller\v1\Order as OrderController;
use app\api\model\InterfaceLog;
use app\api\model\Order as OrderModel;
use app\api\model\Subscribe as SubscribeModel;
use app\api\service\Car as CarInterface;
use app\lib\enum\CarActionEnum;
use app\lib\enum\ZtEnum;
use think\Db;
use think\Exception;
use think\Request;

class Subscribe extends Common
{
    public function index()
    {
        $map = [];
        $data = ['company_id' => ''];
            //页码
        $pageNum = 1;
        if (Request::instance()->isPost()) {
            $data = input('post.');
            if (!empty($data['start_time']) && !empty($data['end_time'])) {
                $map['date_date'] = ['between time', [$data['start_time'], $data['end_time']]];
            } elseif (!empty($data['start_time']) && empty($data['end_time'])) {
                $map['date_date'] = ['>= time', $data['start_time']];
            } elseif (empty($data['start_time']) && !empty($data['end_time'])) {
                $map['date_date'] = ['<= time', $data['end_time']];
            }
            if (is_numeric(input('post.pageNum'))) {
                $pageNum = input('post.pageNum');
            }
            if (!empty($data['company_id'])) {
                $map['company_id'] = $data['company_id'];
            }
        }
        $data['pageNum'] = $pageNum;
        //每页数量
        $numPerPage = config('num_per_page');
        $data['numPerPage'] = $numPerPage;
        $model = new \app\admin\model\Subscribe();
        //列表数据
        $list = $model->getSubscribeList($pageNum, $numPerPage, $map);
        $data['list'] = $list;
        //数据总数
        $count = $model->getSubscribeCount($map);
        $data['count'] = $count;
        $data['company'] = db('company')->field('id, company_name')->where('is_delete', 0)->where('is_use', 1)->select();
        return view('', $data);
    }

    // 添加
    public function add()
    {
        $data = [];
        $data['time_state'] = db('time_state')->select();
        $data['minDate'] = db('date')->order('id')->limit(1)->value('date_date');
        $data['maxDate'] = db('date')->order('id desc')->limit(1)->value('date_date');
        $data['company'] = db('company')->field('id, company_name')->where('is_use', '=', '1')->where('is_delete', '=', '0')->select();
        return view('', $data);
    }

    //执行添加
    public function addSubscribe()
    {
        $data = input('post.');
        $model = new \app\admin\model\Subscribe();
        try {
            $model->doAdd_subscribe($data);
        } catch (Exception $e) {
            return json([
                'statusCode' => 300,
                'message'    => $e->getMessage(),
            ]);
        }
        return json([
            'statusCode'   => 200,
            'message'      => '添加成功',
            'navTabId'     => 'SubscribeListManage',
            'callbackType' => 'closeCurrent',
        ]);
    }

    /**
     * 查看订单详情
     */
    public function detail()
    {
        $data = input('get.');
        $model = new \app\admin\model\Subscribe();
        $company_id = $data['company_id'];
        $data['subscribe_num'] =  Db::name('company')->where('id', '=', $company_id)->value('subscribe_num');
        if(45 == $data['company_id']){
            $data['subscribe_num_gas'] =  Db::name('company')->where('id', '=', $company_id)->value('subscribe_num_gas');
            $data['subscribe_num_diesel'] =  Db::name('company')->where('id', '=', $company_id)->value('subscribe_num_diesel');
        }
        $data['subscribe'] = $model->getDetail($data);
        return view('', $data);
    }

    //执行修改
    public function editSubscribe()
    {
        $data = input('post.');
        $model = new \app\admin\model\Subscribe();
        try {
            $model->doEdit_subscribe($data);
        } catch (Exception $e) {
            return json([
                'statusCode' => 300,
                'message'    => $e->getMessage(),
            ]);
        }
        return json([
            'statusCode'   => 200,
            'message'      => '修改成功',
            'navTabId'     => 'SubscribeListManage',
            'callbackType' => 'closeCurrent',
        ]);
    }

    // 执行删除
    public function doDelete()
    {
        $userId = input('get.id');
        $subscribe = new \app\admin\model\Subscribe();
        try {
            $subscribe->doDelete($userId);
        } catch (Exception $e) {
            return json([
                'statusCode' => 300,
                'message'    => $e->getMessage(),
            ]);
        }
        return json([
            'statusCode' => 200,
            'message'    => '删除成功',
            'navTabId'   => 'SubscribeListManage',
        ]);
    }

    public function num()
    {
        $data['list'] = Db::name('company')->field('id, company_name, subscribe_num, subscribe_num_gas, subscribe_num_diesel')->where('is_use', '=', 1)->where('is_delete', '=', 0)->select();
        return view('', $data);
    }

    public function editNum()
    {
        $data = input('post.');
        // $data = [
        //     'subscribe_num'        => [0 => '4', 1 => '4', 2 => '4', 3 => '5', 4 => '4', 5 => '6', 6 => '6',],
        //     'subscribe_num_gas'    => [0 => '0', 1 => '0', 2 => '0', 3 => '4', 4 => '0', 5 => '0', 6 => '0',],
        //     'subscribe_num_diesel' => [0 => '0', 1 => '0', 2 => '0', 3 => '5', 4 => '0', 5 => '0', 6 => '0',],
        //     'id'                   => [0 => '36', 1 => '38', 2 => '39', 3 => '45', 4 => '48', 5 => '49', 6 => '54',],
        // ];
        foreach ($data['id'] as $key => $item) {
            $company_id = $data['id'][$key];
            $subscribe_num = $data['subscribe_num'][$key]; // 修改后的默认台数:10
            $old_num = Db::name('company')->where('id', '=', $company_id)->value('subscribe_num'); // 原来的默认台数:4
            Db::name('company')->where('id', '=', $company_id)->setField('subscribe_num', $subscribe_num);
            // 修改后的大于原来的
            if ($subscribe_num > $old_num) {
                $num = $subscribe_num - $old_num; // 6 - 4 = 2
                Db::name('subscribe')->where('company_id', '=', $company_id)->where('date_id', '>=', static function ($query) {
                    $query->name('date')->field('id')->where('date_date', '=', date('Y-m-d'));
                })->inc('num', $num)->update();
                // 修改后的小于原来的
            } elseif ($subscribe_num < $old_num) {
                $num = $old_num - $subscribe_num; // 6 - 4 = 2
                Db::name('subscribe')->where('company_id', '=', $company_id)->where('date_id', '>=', static function ($query) {
                    $query->name('date')->field('id')->where('date_date', '=', date('Y-m-d'));
                })->update([
                    'num' => Db::raw("IF(num < {$num}, 0, num - {$num})"),
                ]);
            }
            if (45 == $company_id) {
                $subscribe_num_gas = $data['subscribe_num_gas'][$key]; // 10
                $old_num_gas = Db::name('company')->where('id', '=', $company_id)->value('subscribe_num_gas'); // 5
                Db::name('company')->where('id', '=', $company_id)->setField('subscribe_num_gas', $subscribe_num_gas);
                if ($subscribe_num_gas > $old_num_gas) {
                    $num_gas = $subscribe_num_gas - $old_num_gas;
                    Db::name('subscribe')->where('company_id', '=', $company_id)->where('date_id', '>', static function ($query) {
                        $query->name('date')->field('id')->where('date_date', '=', date('Y-m-d'));
                    })->inc('num_gas', $num_gas)->update();
                } elseif ($subscribe_num_gas < $old_num_gas) {
                    $num_gas = $old_num_gas - $subscribe_num_gas;
                    Db::name('subscribe')->where('company_id', '=', $company_id)->where('date_id', '>', static function ($query) {
                        $query->name('date')->field('id')->where('date_date', '=', date('Y-m-d'));
                    })->update([
                        'num_gas' => Db::raw("IF(num_gas < {$num_gas}, 0, num_gas - {$num_gas})"),
                    ]);
                }
                $subscribe_num_diesel = $data['subscribe_num_diesel'][$key]; // 10
                $old_num_diesel = Db::name('company')->where('id', '=', $company_id)->value('subscribe_num_diesel'); // 5
                Db::name('company')->where('id', '=', $company_id)->setField('subscribe_num_diesel', $subscribe_num_diesel);
                if ($subscribe_num_diesel > $old_num_diesel) {
                    $num_diesel = $subscribe_num_diesel - $old_num_diesel;
                    Db::name('subscribe')->where('company_id', '=', $company_id)->where('date_id', '>', static function ($query) {
                        $query->name('date')->field('id')->where('date_date', '=', date('Y-m-d'));
                    })->inc('num_diesel', $num_diesel)->update();
                } elseif ($subscribe_num_diesel < $old_num_diesel) {
                    $num_diesel = $old_num_diesel - $subscribe_num_diesel;
                    Db::name('subscribe')->where('company_id', '=', $company_id)->where('date_id', '>', static function ($query) {
                        $query->name('date')->field('id')->where('date_date', '=', date('Y-m-d'));
                    })->update([
                        'num_diesel' => Db::raw("IF(num_diesel < {$num_diesel}, 0, num_diesel - {$num_diesel})"),
                    ]);
                }
            }
        }
        return json([
            'statusCode'   => 200,
            'message'      => '修改成功',
            'navTabId'     => 'SubscribeNumManage',
            'callbackType' => 'closeCurrent',
        ]);
    }

    public function timeState()
    {
        $data['list'] = Db::name('time_state')->order('time_state')->select();
        return view('', $data);
    }

    public function addTimeState()
    {
        return view('');
    }

    public function doTimeStateAdd()
    {
        $data['time_state'] = input('post.time_state');
        $subscribe = new \app\admin\model\Subscribe();
        try {
            $subscribe->doTimeStateAdd($data);
        } catch (Exception $e) {
            return json([
                'statusCode' => 300,
                'message'    => $e->getMessage(),
            ]);
        }
        return json([
            'statusCode'   => 200,
            'message'      => '添加成功',
            'navTabId'     => 'TimeStateManage',
            'callbackType' => 'closeCurrent',
        ]);
    }

    public function editTimeState()
    {
        $data['id'] = input('get.id');
        $data['time_state'] = Db::name('time_state')->where('id', $data['id'])->value('time_state');
        return view('', $data);
    }

    public function doTimeStateEdit()
    {
        $data['id'] = input('post.id');
        $data['time_state'] = input('post.time_state');
        $subscribe = new \app\admin\model\Subscribe();
        try {
            $subscribe->doTimeStateEdit($data);
        } catch (Exception $e) {
            return json([
                'statusCode' => 300,
                'message'    => $e->getMessage(),
            ]);
        }
        return json([
            'statusCode'   => 200,
            'message'      => '修改成功',
            'navTabId'     => 'TimeStateManage',
            'callbackType' => 'closeCurrent',
        ]);
    }

    /**
     * @Desc 是否开启预约功能
     * @return \think\response\Json|\think\response\View
     */
    public function menu()
    {
        $data = Db::name('base_subscribe_num')->find();
        return view('', $data);
    }

    /**
     * @Desc 是否开启预约功能
     * @return \think\response\Json|\think\response\View
     */
    public function editMenu()
    {
        $data = input('post.');
        Db::name('base_subscribe_num')->where('id', '=', $data['id'])->update(['is_use' => $data['is_use']]);
        return json([
            'statusCode'   => 200,
            'message'      => '修改成功',
            'navTabId'     => 'SubscribeManage',
            'callbackType' => 'closeCurrent',
        ]);
    }

    // public function delTimeState()
    // {
    //     $id = input('get.id');
    //     db('time_state')->delete($id);
    //     return json([
    //         'statusCode' => 200,
    //         'message' => '删除成功',
    //         'navTabId' => 'TimeStateManage',
    //     ]);
    // }
    /**
     * 启用-禁用
     */
    public function on_off()
    {
        $userId = input('get.id');
        $statusid = input('get.status');
        if ($statusid == 0) {
            $data['id'] = $userId;
            $data['status'] = 0;
            $status = "禁用";
        }
        if ($statusid == 1) {
            $data['id'] = $userId;
            $data['status'] = 1;
            $status = "启用";
        }
        try {
            $Company = new \app\admin\model\Subscribe();
            $Company->editStatus($data);
        } catch (Exception $e) {
            return json([
                'statusCode' => 300,
                'message'    => $e->getMessage(),
            ]);
        }
        return json([
            'statusCode' => 200,
            'message'    => $status . '成功',
            'navTabId'   => 'TimeStateManage',
        ]);
    }

    public function changeStatus()
    {
        $date_id = input('get.date_id');
        $company_id = input('get.company_id');
        try {
            $date_date = Db::name('date')->where('id', '=', $date_id)->value('date_date');
            // 1.取消当天所有预约订单
            $lshList = Db::name('order')->field('order_id, lsh')->where('company_id', '=', $company_id)->where('zt', '=', ZtEnum::SUCCESS)->whereTime('subscribe_date', 'between', [strtotime($date_date), strtotime($date_date) + 86399])->select();
            $order = new OrderController();
            foreach ($lshList as $lsh) {
                $this->cancelCarOrder($lsh['lsh']);
                OrderModel::cancelOrder($lsh['order_id']);
                $order->generatePaymentCancelData($lsh['order_id']);
            }
            // 2.将当天的预约数量改成0
            Db::name('subscribe')->where('date_id', '=', $date_id)->where('company_id', '=', $company_id)->update([
                'num'        => 0,
                'num_gas'    => 0,
                'num_diesel' => 0,
            ]);
        } catch (Exception $e) {
            return json([
                'statusCode' => 300,
                'message'    => $e->getMessage(),
            ]);
        }
        return json([
            'statusCode' => 200,
            'message'    => '修改成功',
            'navTabId'   => 'SubscribeListManage',
        ]);
    }
    /**
     * @Desc 取消预约检车
     *
     * @param $lsh
     *
     * @return array
     */
    private function cancelCarOrder($lsh)
    {
        $data = json_encode(['lsh' => $lsh], JSON_UNESCAPED_UNICODE);
        $param = [
            'action' => CarActionEnum::CANCEL_SUBSCRIBE,
            'data'   => $data,
        ];
        $car = new CarInterface($param);
        $result = $car->appointment();
        $logData = [
            'code'  => CarActionEnum::CANCEL_SUBSCRIBE,
            'title' => '取消预约信息',
            'limit' => CarActionEnum::CANCEL_SUBSCRIBE_NUM,
        ];
        $this->addInterfaceLog($logData);
        if (1 == $result['code']) {
            OrderModel::update(['zt' => ZtEnum::CANCELLED], ['lsh' => $lsh]);
            $subscribe_id = Db::name('order')->where('lsh', '=', $lsh)->value('subscribe_id');
            if (45 == $this->order['company_id'] && 1 == $this->order['vehicle_id']) {
                (new SubscribeModel())->where('id', '=', $subscribe_id)->inc('num_gas')->update();
            } elseif (45 == $this->order['company_id'] && (2 == $this->order['vehicle_id'] || 3 == $this->order['vehicle_id'])) {
                (new SubscribeModel())->where('id', '=', $subscribe_id)->inc('num_diesel')->update();
            } else {
                (new SubscribeModel())->where('id', '=', $subscribe_id)->inc('num')->update();
            }
        }
        return $result;
    }


    /**
     * @Desc 增加接口调用次数
     *
     * @param $param
     */
    public function addInterfaceLog($param)
    {
        $param['date'] = date('Y-m-d');
        if (!array_key_exists('num', $param)) {
            $param['num'] = 1;
        }
        if (!InterfaceLog::getDetail($param)) {
            InterfaceLog::insertData($param);
        } else {
            InterfaceLog::addNum($param);
        }
    }

    // 添加
    public function date()
    {
        $data = [];
        $data['minDate'] = db('date')->order('id')->limit(1)->value('date_date');
        $data['maxDate'] = db('date')->order('id desc')->limit(1)->value('date_date');
        return view('', $data);
    }

    // 添加
    public function dateDoit()
    {
        $date_date = input('post.date_date');
        Db::name('date')->where('date_date', '=', $date_date)->setField('is_show', 0);
    }
}